<?php
/**
 * Created by IntelliJ IDEA.
 * User: Administrator
 * Date: 2020/3/5
 * Time: 9:40
 */

namespace app\index\controller;


use app\IndexBaseController;
use GatewayClient\Gateway;
use think\facade\Db;
use tools\MyHelp;
use tools\RoomCache;

class Room extends IndexBaseController
{
    private static $link = array(
        "http://caiji.kuyun98.com/inc/ldg_kkm3u8.php",
        "http://www.zdziyuan.com/inc/s_api_zuidam3u8.php",
        "http://www.1977zy.com/inc/97m3u8.php",
        "http://api.172zy.xyz/inc/172m3u8.php",
        "http://www.zdziyuan.com/inc/s_apidown.php",
        "http://zy.bajieziyuan.com/inc/bjm3u8.php",
    );

    function create()
    {
        $updata = $this->reqdata;
        unset($updata['client_id']);
        $updata['opentime'] = $this->request->server('REQUEST_TIME');
        if ($updata['status'] == 1 && array_key_exists('password', $updata)) $updata['password']='';
        $updata['owner_id'] = $this->userinfo['id'];
        $updata['people'] = 1;
        $updata['playing'] = '';
        $res = [
            'bool' => false,
            'msg' => '服务器错误请重试'
        ];
        if ($this->userinfo['grade_id'] != 1) {
            $res['msg'] = '房间资源耗尽，请稍后再试';
            $where = [
                ['status', '=', 3],
                ['id', '<=', 100]
            ];

            for ($i = 0; $i < 3; $i++) {
                $room = Db::name('room')->where($where)->limit(1)->find();
                if (!empty($room)) {
                    $a = Db::name('room')->where(['id' => $room['id'], 'status' => 3])->update($updata);
                    if ($a !== 0) {
                        $res['bool'] = true;
                        break;
                    }
                }
            }
        } else {
            $a = Db::name('room')->insertGetId($updata);
            $room = [
                'id' => $a,
            ];
            $res['bool'] = true;
        }

        if ($res['bool']) {
            $client = $this->reqdata['client_id'];
            Gateway::joinGroup($this->reqdata['client_id'], $room['id']);
            Gateway::setSession($client,['roomid'=>$room['id'],'uid'=>$this->userinfo['id']]);
            $roomcache = new RoomCache($this->app->getRuntimePath());
            $roomcache->setData($updata,$room['id']);
            $this->success(['room' => $room['id']]);
        } else {
            $this->error($res['msg']);
        }
    }

    function index()
    {
        if ($this->request->method() == 'GET') {
            switch ($this->param['type']){
                case 'single':
                    break;
                case 'online':
                    break;
                default :
                    abort(404,'页面不存在');
            }
            $api = Db::name('play_api')->field('name,url,selected')->where(['status' => 1])->select();
            $temdata['api'] = $api;
            $temdata['selectedapi'] = '';
            foreach ($api as $v){
                if($v['selected']==1){
                    $temdata['selectedapi'] = $v['url'];
                    break;
                }
            }
            $temdata['link'] = self::$link;
            $temdata['type'] = $this->param['type'];
            return view('index', $temdata);
        } else {

        }
    }

    function join()
    {
        $room = Db::name('room')->find($this->param['roomid']);
        if($this->request->isGet()){
            $roomcache = new RoomCache($this->app->getRuntimePath());
            $roomcache->setData($room,$room['id']);
            if($room && $room['status'] !=0 && $room['status'] !=3){
                if($room['people']>=$room['canpeople']){
                    return view('/error',['msg'=>'房间人员已满，请换房间','time'=>5,'url'=>'/']);
                }
                $api = Db::name('play_api')->field('name,url,selected')->where(['status' => 1])->select();
                $temdata['api'] = $api;
                $temdata['selectedapi'] = '';
                foreach ($api as $v){
                    if($v['selected']==1){
                        $temdata['selectedapi'] = $v['url'];
                        break;
                    }
                }
                $temdata['type'] = 'join';
                $temdata['roomId'] = $room['id'];
                $temdata['roomStatus'] = $room['status'];
                $temdata['master'] = $room['owner_id'] == $this->request->userinfo['id'] ? 1 : 0;
                $temdata['link'] = self::$link;
                return view('index', $temdata);
            }
            return view('/error',['msg'=>'房间不存在，或已关闭','time'=>5,'url'=>'/']);
        }else{
            $pwd = $this->reqdata['password'];
            if($room['status']==0 || $room['status']==3){
                $this->error('房间已关闭');
            }
            if($room['people']>=$room['canpeople']){
                $this->error('来晚了，房间人员已满');
            }
            if($room['status']==2){
                if($room['password']!=$pwd){
                    $this->error('房间密令错误');
                    die();
                }
            }
//          绑定房间
            $client = $this->reqdata['client_id'];
            Gateway::joinGroup($client,$this->param['roomid']);
            Gateway::sendToGroup($this->param['roomid'],json_encode(['type'=>'menberJoin','userinfo'=>$this->userinfo]));
            Gateway::setSession($client,['roomid'=>$this->param['roomid'],'uid'=>$this->userinfo['id']]);
            $this->success(['roominfo'=>$room]);
        }
    }

    function closeRoom(){

    }
}